package com.chaos.framework.web.exception;

import com.chaos.framework.model.dto.result.Result;
import com.chaos.framework.model.dto.result.ResultEnum;
import com.chaos.framework.model.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalDefultExceptionHandler {


    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Result illegalArgumentException(IllegalArgumentException e) {
        Result result = new Result();
        result.failure();
        result.msg(ResultEnum.VALIDATE.getCode(), e.getMessage());
        log.warn("[框架]: 内部错误编码[{}],错误信息[{}]", result.getCode(), e.getMessage());
        return result;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result businessException(BusinessException e) {
        log.warn(e.getMessage());
        Result result = e.getResult();
        log.warn("[框架]: 业务异常编码[{}],错误信息[{}]", result.getCode(), result.getMsg());
        return result;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public Result duplicateException(DuplicateKeyException e) {
        Result result = new Result();
        result.failure();
        result.msg(ResultEnum.SQL_DUPLICATE_KEY.getCode(), ResultEnum.SQL_DUPLICATE_KEY.getDefaultMsg());
        log.warn("[框架]: 内部错误编码[{}],错误信息[{}]", result.getCode(), result.getMsg());
        return result;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result defultExcepitonHandler(Exception e) {
        Result result = new Result();
        result.unknow();
        log.error("错误编码[{}],错误信息[{}],{}", result.getCode(), result.getMsg(), e);
        return result;
    }
}

